<script setup>
import {uploadFile} from '@/api/http/commom.js'
import {ref} from "vue";
import {ElMessage} from "element-plus";
import {userInfo} from '@/stores/userStore.js'

const fileList = defineModel("fileList", {default: []})


const {limitType, limitSize, width, uploadType} = defineProps({
  limitType: {
    default: ".png,.img,.dmg"
  },
  limitSize: {
    default: 1//单位为MB
  },
  width: {
    default: '80%'
  },
  uploadType: {
    default: "global"
  }
})

const fileUploadRef = ref();

const updateFileFunc = async (param) => {
  const formData = new FormData();
  formData.append("file", param.file);
  formData.append("uploadType", uploadType);
  formData.append("userInfo", JSON.stringify(userInfo().$state));
   uploadFile(formData)
      .then(res => {
        param.onSuccess(res.data);
      })
      .catch(res => {
        param.onError("上传错误");
      })

}

const initFunc = () => {
  fileUploadRef.value.clearFiles();
}

const beforeUploadValid = (param) => {
  const b2Mb = 1000 * 1000;
  const sizeLimitFlag = (param.size / b2Mb) >= limitSize;
  if (sizeLimitFlag) {
    ElMessage({
      type: "error",
      message: `文件:【${param.name}】过大不可上传,限制:${limitSize}MB,当前文件:${(param.size / b2Mb).toFixed(1)}MB`
    })
    return false;
  }
  return true;
}


defineExpose({
  initFunc
})
</script>

<template>

  <el-upload
      ref="fileUploadRef"
      v-model:file-list="fileList"
      :style="`width:${width}`"
      multiple
      drag
      :accept="limitType"
      :http-request="updateFileFunc"
      :before-upload="beforeUploadValid"
  >
    <div>
      <el-icon size="50px">
        <UploadFilled/>
      </el-icon>
      <span style="display: block">拖拽或点击这里上传文件</span>
    </div>
    <template #tip>
      <el-text type="info">{{
          `目前支持${limitType}格式，且不超过${limitSize}MB的文件`
        }}
      </el-text>
    </template>
  </el-upload>

</template>

<style scoped lang="scss">

</style>